package com.manong.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manong.aspect.AutoFill;
import com.manong.entity.Department;
import com.manong.entity.LoginLog;
import com.manong.entity.Notice;
import com.manong.entity.Role;
import com.manong.service.NoticeService;
import com.manong.utils.JwtUtils;
import com.manong.utils.Result;
import com.manong.vo.query.LoginLogQueryVo;
import com.manong.vo.query.NoticeVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/api/notice")
public class NoticeController {

    @Resource
    private NoticeService noticeService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private JwtUtils jwtUtils;

    /**
     * 查询登录日志列表
     * @param noticeVo
     * @return
     */
    @GetMapping("/list")
    public Result list(NoticeVo noticeVo){
        IPage<Notice> page = new Page<Notice>();
        page.setCurrent(noticeVo.getPageNo());
        page.setSize(noticeVo.getPageSize());
        noticeService.findNoticeListByUsername(page,noticeVo);
        return Result.ok(page);
    }

    /**
     * 发布通知公告
     * @param notice
     * @return
     */
    @AutoFill(menu = "通知公告", type = "发布")
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:notice:add')")
    public Result add(@RequestBody Notice notice){
        String username = jwtUtils.getUsernameFromToken(request.getHeader("token"));
        notice.setUsername(username);
        notice.setCreateTime(new Date());
        if(noticeService.save(notice)){
            return Result.ok().message("发布成功");
        }else{
            return Result.error().message("发布失败");
        }
    }

    @AutoFill(menu = "通知公告", type = "修改")
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:notice:edit')")
    public Result update(@RequestBody Notice notice){
        notice.setCreateTime(new Date());
        //调用修改方法
        if(noticeService.updateById(notice)){
            return Result.ok().message("修改成功");
        }
        //返回数据
        return Result.error().message("修改失败");
    }

    @AutoFill(menu = "通知公告", type = "删除")
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:notice:delete')")
    public Result delete(@PathVariable Long id){
        if(noticeService.deleteById(id)){
            return Result.ok().message("删除成功");
        }else{
            return Result.error().message("删除失败");
        }
    }
}
